import requests
import time
import random
import re

def main():
    headers = {
        'authority': 'm.weibo.cn',
        'accept': 'application/json, text/plain, */*',
        'mweibo-pwa': '1',
        'x-xsrf-token': 'ef415d',
        'x-requested-with': 'XMLHttpRequest',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://m.weibo.cn/status/4667922453367011',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cookie': 'SCF=Ag0zIXNj9sw_TETdBedbfI5QDWZk3T5Q3IttKVe9TgEQEgQwrWUQri-zJOfytJ9PJdeoxoJFwjLYVulu7aLEKnw.; SUB=_2A25MF6N3DeRhGedH7VsR-C_IzjuIHXVv-80_rDV6PUJbktCOLWTmkW1NULJrnBJtVBKsmRUCCQjQxRK-S_2yc4lu; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5zwlQBan7iwfo1.JyAXnNF5NHD95Qp1Kq4ehnpSh-NWs4DqcjZgrxydEXEShikC5tt; MLOGIN=1; _T_WM=32716449064; WEIBOCN_FROM=1110006030; M_WEIBOCN_PARAMS=oid=4667922453367011&luicode=20000061&lfid=4667922453367011; XSRF-TOKEN=3d3b82'
    }

    try:
        url = r'https://m.weibo.cn/comments/hotflow?id=4667922251517087&mid=4667922251517087&max_id_type=0'
        for page in range(10000):
            response = requests.get(url, headers=headers)

            for i in response.json()['data']:
                neirong = re.sub(r'<[^>]*>', '', i['text'])
                with open(r'test.txt', 'a', encoding='utf-8') as f:
                    if neirong is not None:
                        f.write(f'{neirong}\n')

                max_id = str(response.json()['data']['max_id'])
                max_id_type = str(response.json()['data']['max_id_type'])
                url = 'https://m.weibo.cn/comments/hotflow?id=4667922251517087&mid=4667922251517087&max_id='+max_id+'&max_id_type='+max_id_type
            print('已写完第' + str(page + 1) + '页评论')
            if max_id == '0':
                break

            # time.sleep(random.randint(2, 4))
    except:
        pass


if __name__ == '__main__':
    main()
